<template>
  <div style="height: 5vh">
    <div class="addButton" v-if="showAddBtn">
      <van-button
        round
        type="info"
        @click="(showAdd = true), (showAddBtn = false)"
      >
        <van-icon name="plus" />
      </van-button>
    </div>

    <van-pull-refresh
      v-model="pullOption.refreshing"
      @refresh="onRefresh()"
      :immediate-check="false"
    >
      <van-list
        v-model="pullOption.loading"
        :finished="pullOption.finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-sticky>
          <van-search
            v-model="searchForm.keyword"
            @search="onSearch"
            placeholder="请输入搜索关键词"
          />
        </van-sticky>
        <van-cell v-for="(item, index) in pageData.record" :key="item.id" class="card">
          <van-row @click="showArticleInfo(item)">
            <van-col span="4">
              <van-image
                round
                width="3rem"
                height="3rem"
                :src="item.createUserAvatar"
              />
            </van-col>
            <van-col span="8">
              <span class="article-username">{{ item.createUserNickname }}</span
              ><br /><span class="categoryName">#{{ item.category.name }}</span>
              <br />
            </van-col>
            <van-col span="11">
              &nbsp;&nbsp;<van-icon
                v-if="item.topping == 1"
                name="fire-o"
                color="#ee0a24"
                size="20"
              />
            </van-col>
            <van-col span="1"
              >
              <span v-if="(item.createUser == loginUser.id)" @click.stop="delArticle(item.id, index)" style="color:red;font-size:1.5em">x</span><br />
              <!-- <van-badge content="Topping" /> -->
            </van-col>
          </van-row>
          <van-row @click="showArticleInfo(item)">
            {{ item.title }}
          </van-row>
          <van-row> </van-row>
          <van-row
            class="imgBox"
            v-if="item.fileList3[0] && item.fileList3[0].length > 0"
          >
            <van-col
              :span="8"
              v-for="(url, index) in item.fileList3"
              :key="url"
            >
              <van-image
                :src="url"
                width="100%"
                @click="imagePreview(item.fileList3, index)"
              >
                <template v-slot:error>图片加载失败</template>
              </van-image>
            </van-col>
          </van-row>
          <span class="create-time">{{ item.createTime }}</span>

          <van-row style="text-align: center; margin-top: 0.5em">
            <van-col span="8">
              <van-icon
                name="good-job-o"
                size="1em"
                v-if="item.likeStatus == 0"
                @click="like(item, 1)"
              />
              <van-icon
                name="good-job"
                size="1em"
                color="#40C0C9"
                v-else
                @click="like(item, 0)"
              />
              {{ item.likedNum }}
            </van-col>
            <van-col span="8">
              <van-icon name="comment-o" size="1em" />0
            </van-col>
            <van-col span="8">
              <van-icon name="share-o" size="1em" />
            </van-col>
          </van-row>
        </van-cell>
      </van-list>
    </van-pull-refresh>

    <van-popup
      @close="showAddBtn = true"
      v-model="showAdd"
      position="bottom"
      close-icon-position="top-left"
      id="add-pop"
    >
      <van-row style="width: 100%; margin: auto">
        <van-col
          span="8"
          offset="8"
          style="text-align: center; font-size: 1.1 em; line-height: 32px"
        >
          发布帖子
        </van-col>
        <van-col span="8" style="text-align: right">
          <van-button
            @click="submitAdd"
            type="info"
            size="small"
            :disabled="isUpload || addForm.title.length == 0"
            style="width: 50%"
            >提交</van-button
          >
        </van-col>
      </van-row>

      <van-row>
        <van-form style="margin-top: 2em">
          <van-field
            v-model="addForm.title"
            name="标题"
            label="标题"
            placeholder="标题"
            :rules="[{ required: true, message: '请填写标题' }]"
          />

          <van-field
            v-model="addForm.content"
            rows="2"
            autosize
            label="正文"
            type="textarea"
            placeholder="请输入正文"
            maxlength="100"
            show-word-limit
          />

          <van-field
            readonly
            clickable
            name="picker"
            :value="pickerValue"
            label="分类"
            placeholder="点击选择分类"
            @click="showPicker = true"
          />
          <van-popup v-model="showPicker" position="bottom">
            <van-picker
              value-key="name"
              show-toolbar
              :columns="categorys"
              @confirm="pickerConfirm"
              @cancel="showPicker = false"
            />
          </van-popup>

          <van-field label="图片">
            <template #input>
              <van-uploader
                v-model="addForm.fileList"
                :after-read="afterRead"
                multiple
                :max-count="9"
                :max-size="10 * 1024 * 1024"
                @oversize="onOversize"
              />
            </template>
          </van-field>
        </van-form>
      </van-row>
    </van-popup>

    <van-image-preview
      v-model="imagePreviewOption.showImg"
      :images="imagePreviewOption.images"
      :startPosition="imagePreviewOption.index"
      @change="imagePreviewChange"
      @close="showAddBtn = true"
    >
      <template v-slot:index
        >第{{ imagePreviewOption.currentIndex }}张</template
      >
    </van-image-preview>

    <van-popup
      @close="showAddBtn = true"
      v-model="showArticle"
      position="right"
      id="article-pop"
    >
      <van-row id="article-head">
        <van-col span="8">
          <van-icon
            name="arrow-left"
            color="#1989fa"
            size="1.5em"
            @click="showArticle = false"
          />
        </van-col>
        <van-col span="8" class="xiangqin"> 详情 </van-col>
      </van-row>
      <article-info :article="currentArticle" />
    </van-popup>
  </div>
</template>
<script>
import { Toast, Dialog } from "vant";
import articleInfo from "../components/ArticleInfo.vue";
export default {
  name: "articleListHomePage",
  components: {
    articleInfo,
  },
  data() {
    return {
      loginUser: {},
      showAddBtn: true,
      showArticle: false,
      imagePreviewOption: {
        images: [],
        showImg: false,
        currentIndex: 1,
        index: 0,
      },
      pageData: {
        record: [],
      },
      showAdd: false,
      isUpload: false,
      searchForm: {
        statusList: [0, 1],
        keyword: "",
        current: 1,
        size: 5,
      },
      addForm: {
        title: "",
        content: "",
        fileList: [],
        categoryId: "",
      },
      pullOption: {
        loading: false,
        finished: false,
        refreshing: false,
      },
      categorys: [],
      showPicker: false,
      pickerValue: "",
      currentArticle: {},
    };
  },
  methods: {
    delArticle(id, index) {
      Dialog.confirm({
        message: "是否删除该帖子",
      }).then(() => {
        this.getRequest(`/article/del/${id}`).then(res => {
        if(res.data.status == 200) {
          this.pageData.record.splice(index, 1)
          Toast({type: 'success', message: '删除成功'})
        }
      })
      });
      

    },
    pickerConfirm(value) {
      this.pickerValue = value.name;
      this.addForm.categoryId = value.id;
      this.showPicker = false;
    },
    onLoad() {
      this.pullOption.finished = false;
      this.pullOption.loading = true;
      this.listRequest(this.searchForm).then((res) => {
        if (res.data.data.record.length == 0) {
          this.pullOption.finished = true;
          this.pullOption.loading = false;
          return;
        }
        this.formatLoadData(res.data.data);
        this.pullOption.loading = false;
        this.searchForm.current++;
      });
    },
    formatLoadData(pageData) {
      this.pageData.current = pageData.current;
      this.pageData.size = pageData.size;
      this.pageData.total = pageData.total;
      this.pageData.record.push(...pageData.record);
      this.formatPageData();
    },
    onRefresh() {
      this.pullOption.finished = false;
      this.searchForm.current = 1;
      this.pullOption.refreshing = true;
      this.pageData.record.splice(0);
      this.listData().then(() => {
        this.pullOption.refreshing = false;
        this.searchForm.current++;
      });
    },
    listRequest(params) {
      return this.postRequest("/article/list", params);
    },
    formatPageData() {
      if (this.pageData.record.length < 1) return;
      for (let item of this.pageData.record) {
        if (item.fileList.length && item.fileList.length > 3) {
          item.fileList3 = item.fileList.slice(0, 3);
          continue;
        }
        item.fileList3 = item.fileList;
      }
    },
    listData() {
      return this.listRequest(this.searchForm).then((res) => {
        this.pageData = res.data.data;
        if (this.pageData.record.length == 0) {
          this.pullOption.finished = true;
        }
        this.formatPageData(res.data.data);
      });
    },
    listCategory() {
      this.postRequest("/category/list", { current: -1, size: -1 }).then(
        (res) => {
          if (res.data.status && res.data.status == 200) {
            this.categorys = res.data.data.record;
            this.addForm.categoryId = this.categorys[0].id;
            this.pickerValue = this.categorys[0].name;
          }
        }
      );
    },
    imagePreview(list, index) {
      this.showAddBtn = false;
      this.imagePreviewOption.showImg = true;
      this.imagePreviewOption.images = list;
      this.imagePreviewOption.currentIndex = index + 1;
      this.imagePreviewOption.index = index;
    },
    imagePreviewChange(index) {
      this.imagePreviewOption.currentIndex = index + 1;
    },
    onSearch() {
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      this.searchForm.current = 1;
      this.listData().then(Toast.clear());
    },
    afterRead(file) {
      this.isUpload = true;
      file.status = "uploading";
      file.message = "上传中...";
      this.uploadFileRequest("/article/uploadImg", file)
        .then((result) => {
          if (result && result.status == 200) {
            file.status = "";
            file.message = "";
            file.url = result.data.data;
          } else {
            file.status = "failed";
            file.message = "上传失败";
          }
          this.isUpload = false;
        })
        .catch(() => {
          file.status = "failed";
          file.message = "上传失败";
          this.isUpload = false;
        });
    },
    submitAdd() {
      this.isUpload = true;
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      let fileUrls = "";
      for (let i = 0; i < this.addForm.fileList.length; i++) {
        if(!this.addForm.fileList[i].url) {
          continue;
        }
        fileUrls += this.addForm.fileList[i].url;
        if (i != this.addForm.fileList.length - 1) {
          fileUrls += ",";
        }
      }
      this.addForm.fileUrls = fileUrls;
      this.postRequest("/article/add", this.addForm).then((res) => {
        if (res.data.status == 200) {
          Toast.success("发表成功");
          this.addForm = {
            title: "",
            content: "",
            fileList: [],
            categoryId: this.categorys[0].id,
          };
          this.pickerValue = this.categorys[0].name;
        }
        this.showAdd = false;
        this.showAddBtn = true;
        this.isUpload = false;
        this.onRefresh();
      });
    },
    onOversize() {
      Toast("文件大小不能超过10MB");
    },
    showArticleInfo(article) {
      this.showArticle = true;
      this.showAddBtn = false;
      this.currentArticle = article;
    },
    like(item, type) {
      item.likeStatus = type;
      if (type == 0) {
        item.likedNum--;
      } else {
        item.likedNum++;
      }
      this.postRequest("/article/like", {
        articleId: item.id,
        likeStatus: type,
      });
    },
    showOneArticle(id){
      this.$emit('change')
      this.getRequest(`/article/getById/${id}`).then(res=>{
        this.showArticleInfo(res.data.data)
      })
    }
  },
  created() {
    this.loginUser = JSON.parse(localStorage.getItem('loginUser'))
    this.listCategory();
    if(this.$route.query.id) {
      this.showOneArticle(this.$route.query.id)
    }
  },
};
</script>
<style scoped>
.addButton {
  position: fixed;
  bottom: 6em;
  right: 1em;
  z-index: 999999;
}
.articleUsername {
  font-weight: bold;
}
.create-time {
  color: #e3d9ca;
}
#add-pop {
  background: #f7f8fa;
  height: 70%;
  padding: 16px;
  box-sizing: border-box;
}
#article-pop {
  background: #f7f8fa;
  width: 100%;
  height: 100%;
}
.xiangqin {
  text-align: center;
  font-weight: 700;
  font-size: 1.2em;
}
#article-head {
  background-color: #fff;
  padding: 0.7em 0.5em;
}
</style>
